#include <stdio.h>
#include <stdint.h>
#include <rte_eal.h>
#include <rte_ethdev.h>
#include <rte_ip.h>
#include <rte_mbuf.h>

#define NUM_MBUFS 8191
#define MBUF_SIZE (sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM)

static uint16_t port_id;

static void process_packet(struct rte_mbuf * mbuf){
    struct rte_ether_hdr * ethdr = rte_pktmbuf_mtod(mbuf, struct rte_ether_hdr *);
    if(ethdr->ether_type == rte_cpu_to_be_16(RTE_ETHER_TYPE_IPV4)){
        struct rte_ipv4_hdr * iphdr = rte_pktmbuf_mtod_offset(mbuf, struct rte_ipv4_hdr *, sizeof(struct rte_ether_hdr)); 

        printf("Received IPv4 packet: src=%u.%u.%u.%u dst=%u.%u.%u.%u\n",
            (ipv4_hdr->src_addr >> 24) & 0xFF,
            (ipv4_hdr->src_addr >> 16) & 0xFF,
            (ipv4_hdr->src_addr >> 8) & 0xFF,
            (ipv4_hdr->src_addr) & 0xFF,
            (ipv4_hdr->dst_addr >> 24) & 0xFF,
            (ipv4_hdr->dst_addr >> 16) & 0xFF,
            (ipv4_hdr->dst_addr >> 8) & 0xFF,
            (ipv4_hdr->dst_addr) & 0xFF);

    }

    rte_pktmbuf_free(mbuf);
}



int main(int argc, char **argv) {

    int ret;

    uint16_t nb_rx = 128;
    if(rte_eal_init(argc, argv) < 0){
        // err
    }

    port_id = atoi(argv[1]);
    struct rte_eth_conf port_config_default{.rxmode = {.max_lro_pkt_size=RTE_ETHER_MAX_LEN}};
    if(rte_eth_dev_configure(port_id, 1, 1, &port_config_default) < 0){
        //err
    } 
    if(rte_eth_rx_queue_setup(port_id, queue_id, nb_rx, rte_socket_id(), NULL) < 0){
        //err
    }
    if(rte_eth_dev_start(port_id) < 0){
        //err
    }
    while(1){
        struct rte_mbuf * mbuf[MBUF_SIZE];
        uint16_t rx_count = rte_eth_rx_burst(port_id, queue_id, mbuf, MBUF_SIZE);
        for(int i = 0; i < rx_count; i++){
            process_packet(mbuf[i]);
        }
    }

    return ret;
}
